import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Router from "vue-router";

const whiteList = ['/login', '/auth-redirect', '/test', '/test2'] // no redirect whitelist

NProgress.configure({showSpinner: false}) // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // document.title = Vue.prototype.Title || ''
  let userInfo = await store.dispatch('app/getUserInfo');
  if (userInfo) {
    // determine whether the user has obtained his permission roles through getInfo
    const hasRoutes = store.getters.routes && store.getters.routes.length > 0
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({path: '/'})
    } else if (hasRoutes) {
      next()
    } else {
      try {
        const routeDatas = await store.dispatch('permission/getRoutes')
        const accessRoutes = await store.dispatch('permission/generateRoutes', routeDatas)
        // dynamically add accessible routes

        router.addRoutes(accessRoutes)

        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({...to, replace: true})
        // next()
      } catch (error) {
        // remove token and go to login page to re-login
        // await store.dispatch('user/resetToken')
        // Message.error(error || 'Has Error')
        // next(`/login?redirect=${to.path}`)
        next()
        // NProgress.done()
      }
    }

  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      // NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})